//
//  MHRootViewController.m
//  MHO
//
//  Created by papo on 2/16/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHRootViewController.h"
#import "MHMenuViewController.h"
#import "MHHomeViewController.h"
#import "MHOptionsViewController.h"
#import "MHLoginViewController.h"
#import "MHRegisterViewController.h"
#import "MHUserInfoViewController.h"
#import "MHEventViewController.h"
#import "MHCollectionViewController.h"
#import "MHDownloadViewController.h"
#import "Lib.h"
#import "MHNewsDetailViewController.h"
#import "MHAppCollectListViewController.h"

@interface MHRootViewController ()
@property (nonatomic, strong) IBOutlet UIView* wifiPassView;
@property (nonatomic, weak) IBOutlet UITextField* wifiPassTf;
@property (nonatomic, weak) IBOutlet UITextView* wifiGuideTv;
@property (nonatomic, strong) NSString* wifiGuide;
@property (nonatomic, weak) IBOutlet UIButton* closeButton;

@end

@implementation MHRootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.menuVc = [[MHMenuViewController alloc] initWithNibName:@"MHMenuViewController" bundle:nil];
    self.leftPanel = self.menuVc;
    self.homeVc = [[MHHomeViewController alloc] initWithNibName:@"MHHomeViewController" bundle:nil];
    self.centerPanel = self.homeVc;
    
    [self checkIpWan];
    self.wifiPassView.layer.cornerRadius = 10;
    self.wifiPassView.layer.borderColor = [[UIColor grayColor] CGColor];
    self.wifiPassView.layer.borderWidth = 2;
    [self.closeButton setTransform:CGAffineTransformMakeRotation(M_PI / 4)];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([Lib isIos7]) {
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.edgesForExtendedLayout = UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight;
        self.automaticallyAdjustsScrollViewInsets = NO;
        
        UIView* view = self.view;
        CGRect frame = view.frame;
        frame.origin.y += 20;
        frame.size.height -= 20;
        view.frame = frame;
//        view.layer.borderColor = [UIColor redColor].CGColor;
//        view.layer.borderWidth = 2;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showHomeVc {
    if (self.centerPanel != self.homeVc) {
        self.centerPanel = self.homeVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showLoginVc {
    if (!self.loginVc) {
        self.loginVc = [[MHLoginViewController alloc] initWithNibName:@"MHLoginViewController" bundle:nil];
        self.loginVc = [[UINavigationController alloc] initWithRootViewController:self.loginVc];
        ((UINavigationController*)self.loginVc).navigationBarHidden = YES;
        [self configureFrame:self.loginVc];
    }
    if (self.centerPanel != self.loginVc) {
        self.centerPanel = self.loginVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showMenuVc {
    [self showLeftPanelAnimated:YES];
}

- (void)showOptionVc {
    if (!self.optionVc) {
        self.optionVc = [[MHOptionsViewController alloc] initWithNibName:@"MHOptionsViewController" bundle:nil];
        self.optionVc = [[UINavigationController alloc] initWithRootViewController:self.optionVc];
        ((UINavigationController*)self.optionVc).navigationBarHidden = YES;
        [self configureFrame:self.optionVc];
    }
    if (self.centerPanel != self.optionVc) {
        self.centerPanel = self.optionVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showUserVc {
    if (!self.userVc) {
        self.userVc = [[MHUserInfoViewController alloc] initWithNibName:@"MHUserInfoViewController" bundle:nil];
        self.userVc = [[UINavigationController alloc] initWithRootViewController:self.userVc];
        ((UINavigationController*)self.userVc).navigationBarHidden = YES;
        [self configureFrame:self.userVc];
    }
    if (self.centerPanel != self.userVc) {
        self.centerPanel = self.userVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showRegisVc {
    if (!self.regisVc) {
        self.regisVc = [[MHRegisterViewController alloc] initWithNibName:@"MHRegisterViewController" bundle:nil];
        self.regisVc = [[UINavigationController alloc] initWithRootViewController:self.regisVc];
        ((UINavigationController*)self.regisVc).navigationBarHidden = YES;
        [self configureFrame:self.regisVc];
    }
    if (self.centerPanel != self.regisVc) {
        self.centerPanel = self.regisVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showEventVc {
    if (!self.eventVc) {
        self.eventVc = [[MHEventViewController alloc] initWithNibName:@"MHEventViewController" bundle:nil];
        self.eventVc = [[UINavigationController alloc] initWithRootViewController:self.eventVc];
        ((UINavigationController*)self.eventVc).navigationBarHidden = YES;
        [self configureFrame:self.eventVc];
    }
    if (self.centerPanel != self.eventVc) {
        self.centerPanel = self.eventVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showCollectionVc {
    if (!self.collectionVc) {
        self.collectionVc = [[MHCollectionViewController alloc] initWithNibName:@"MHCollectionViewController" bundle:nil];
        self.collectionVc = [[UINavigationController alloc] initWithRootViewController:self.collectionVc];
        ((UINavigationController*)self.collectionVc).navigationBarHidden = YES;
    }
    if (self.centerPanel != self.collectionVc) {
        self.centerPanel = self.collectionVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showDownloadVc {
    if (!self.downloadVc) {
        self.downloadVc = [[MHDownloadViewController alloc] initWithNibName:@"MHDownloadViewController" bundle:nil];
        self.downloadVc = [[UINavigationController alloc] initWithRootViewController:self.downloadVc];
        ((UINavigationController*)self.downloadVc).navigationBarHidden = YES;
    }
    if (self.centerPanel != self.downloadVc) {
        self.centerPanel = self.downloadVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)showAppCollectListVc {
    if (!self.appCollectListVc) {
        MHAppCollectListViewController* vc = [[MHAppCollectListViewController alloc] initWithNibName:@"MHAppCollectListViewController" bundle:nil];
        [vc setFavorite:YES];
        
        self.appCollectListVc = [[UINavigationController alloc] initWithRootViewController:vc];
        ((UINavigationController*)self.appCollectListVc).navigationBarHidden = YES;
    }
    if (self.centerPanel != self.appCollectListVc) {
        self.centerPanel = self.appCollectListVc;
    }
    [self showCenterPanelAnimated:YES];
}

- (void)updateUserInfo {
    [self.menuVc updateUserInfo];
}

- (void)configureFrame:(UIViewController*)vc {
    CGRect frame = vc.view.frame;
    frame.origin.y += 20;
    frame.size.height -= 20;
    vc.view.frame = frame;
}


- (BOOL)shouldAutorotate {
    UIViewController* vc = [[self.homeVc.navigationController viewControllers] lastObject];
    if (vc && [vc isKindOfClass:[MHNewsDetailViewController class]]) {
        return YES;
    }
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return UIInterfaceOrientationIsPortrait(toInterfaceOrientation);
}

- (void) checkIpWan {
    self.isMHOWifi = NO;
    [Lib getWANIPAddressWithCompletion:^(NSString *IPAddress) {
        NSLog(@"ip wan: %@", IPAddress);
        // for testing
//        IPAddress = @"27.118.29.70";
        NSString* url = [NSString stringWithFormat:@"%@%@?key=%@", kServerUrl2, kServiceGetIpWan, kServerKey];
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id dict = [parser objectWithString:ret];
        if (dict) {
            int retVal = [dict[@"Ret"] intValue];
            if (retVal > 0) {
                NSArray* data = dict[@"Data"];
                for (NSDictionary* d in data) {
                    if (d) {
                        IPWan* ipwan = [IPWan ipWanWithDictionary:d];
                        if ([ipwan.ipAddress isEqualToString:IPAddress]) {
                            // true
                            self.isMHOWifi = YES;
                            [self getWifiPass];
                            break;
                        }
                    }
                }
            }
        }
    }];
}

- (void)getWifiPass {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/ListCodeTongBu?key=%@", kServerKey];
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        if (ret) {
            SBJsonParser* parser = [[SBJsonParser alloc] init];
            id dict = [parser objectWithString:ret];
            if (dict) {
                NSString* retVal = dict[@"Ret"];
                if (retVal && [retVal integerValue] > 0) {
                    NSArray* data = dict[@"Data"];
                    if (data && data.count > 0) {
                        NSDictionary* d = data[0];
                        NSString* pass = d[@"Link"];
//                        NSString* guide = d[@""];
                        if (pass) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                                            self.wifiPass = pass;
                                [self showWifiPassView];
                                [self.menuVc updateWifiPass:YES pass:pass];
                            });
                            [self updateWifiPassStatus];
                        }
                    }
                }
            }
        }
    });
}

- (void)updateWifiPassStatus {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/ListCodeTongBu?Id=1&key=%@", kServerKey];
    NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
    if (ret) {
        NSLog(@"update wifi status: %@", ret);
    }
}

- (void)showWifiPassView {
    self.wifiPassTf.text = self.wifiPass;
//    self.wifiGuideTv.text = self.wifiGuide;
    if ([self.wifiPassView superview] != nil) {
        [self.wifiPassView removeFromSuperview];
    }
    CGRect frame1 = self.view.frame;
    CGRect frame2 = self.wifiPassView.frame;
    CGRect frame = CGRectMake((frame1.size.width - frame2.size.width) / 2, (frame1.size.height - frame2.size.height) / 2, frame2.size.width, frame2.size.height);
    self.wifiPassView.frame = frame;
    [self.view addSubview:self.wifiPassView];
}

- (IBAction)copyPass:(id)sender {
    if (self.wifiPass) {
        [[UIPasteboard generalPasteboard] setString:self.wifiPass];
        [Lib showMessage:@"Đã copy password vào clipboard!" title:@""];
    }
}

- (IBAction)closeWifiPassView:(id)sender {
    [self.wifiPassView removeFromSuperview];
}
@end
